import router from './router'
import store from './store'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

// 白名单
const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
	NProgress.start()
	const token = store.getters.token
	if (token) {
		if (to.path === '/login') {
			next('/')
		} else {
			if (!store.getters.userId) {
				const { roles } = await store.dispatch('user/getUserInfo')

				// 筛选用户可用的路由
				const routes = await store.dispatch('permission/filterRoutes', roles.menus)

				// 动态路由 添加到 路由表中
				router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
				next(to.path)
			}
			next()
		}
	} else {
		if (whiteList.includes(to.path)) {
			next()
		} else {
			next('/login')
		}
	}
	NProgress.done() // 解决手动切换进度条不关闭进度条
})

// 后置守卫
router.afterEach(() => {
	NProgress.done() // 关闭进度条
})
